package libraries;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;

public class TransPartLibrary {
	protected LinkedList<TransPart> partData = new LinkedList<TransPart>();
	String name;
	
	/**
	 * searches for a part in this library for translation purposes 
	 * @param dev EAGLE device
	 * @param pac EAGLE package
	 * @param lib EAGLE library
	 * @return the TransPart that matches the given parameters
	 */
	public TransPart find(String dev, String pac, String lib) {
		for (TransPart i: partData) {
			if ((dev.equals( i.getDevice())) && (pac.equals(i.getPack())) && (lib.equals(i.getLibrary()))) {
				return i;
			}
		}
		return null;
	}

	public int getSize() {
		return partData.size();
	}
	
	public TransPart get(int index) {
		return partData.get(index);
	}
	
	public void add(TransPart part) {
		partData.add(part);
	}
	
	public TransPartLibrary(String name) {
		super();
		this.partData = new LinkedList<TransPart>();
		this.name = name;
	}
	

	public static TransPartLibrary testLibrary(){
		TransPartLibrary lib = new TransPartLibrary("Test_Library");
		
		LinkedList<String> condConnKey = new LinkedList<String>();
		condConnKey.add("1");
		condConnKey.add("2");
		LinkedList<String> condConnVal = new LinkedList<String>();
		condConnVal.add("p");
		condConnVal.add("n");
		TransConn condConn = new TransConn(condConnKey, condConnVal);
		lib.partData.add(new TransPart("KONDENSATOR_KAPAZITAET_ALLGEMEIN", "KONDENSATOR_KAPAZITAET_ALLGEMEIN", "e-kondensatoren", "", condConn, "Modelica.Electrical.Analog.Basic.Resistor", 1, "R="));
		
		return lib;
	}
	
	/**
	 * writes this library to file
	 * @param file the file name for the export
	 * @throws IOException
	 */
	public void writeLibraryFile(File output) throws IOException{
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter(output));
			out.write("EAGLEModelicaConversionLibrary"+System.getProperty("line.separator"));
			out.write(name);
			for (TransPart t: partData) {
				out.write(System.getProperty("line.separator"));
				out.write(t.toFileString());
			}
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
	
	/**
	 * deletes a TransPart from the library
	 * @param delItem the TransPart to be deleted 
	 */
	public void deletePart(TransPart delItem) {
		partData.remove(delItem);
		
	}

	public String getName() {
		return name;
	}
	public String toString() {
		return name;
	}
}